from tencentcloud.common.common_client import CommonClient
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile

from kj_d1.Config.config import useConfig
import pandas as pd
import numpy as np
import re


def sum_amt(x_list):
    a_au = 0
    for au in x_list:
        try:
            if isinstance(au, str):
                au = float(au.replace(',', ''))
            a_au += au
        except ValueError:
            a_au = au
            break
    return a_au


def get_num_for(f):
    if isinstance(f, float) or isinstance(f, int):
        return '{:,.2f}'.format(f)
    else:
        return f


def request_action(uc, action, params, endpoint="lke.tencentcloudapi.com"):
    """

    :param action:
    :param params:
    :param endpoint:
    :return:
    """
    cred = credential.Credential(uc.secret_id, uc.secret_key)
    httpProfile = HttpProfile()
    httpProfile.endpoint = endpoint
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    common_client = CommonClient("lke", "2023-11-30", cred, uc.region, profile=clientProfile)
    resp = common_client.call_json(action=action, params=params)
    return resp


def par_mk(mk):
    # mk = rep1
    # print(mk)
    res_txt = mk.split('\n')
    res_txt2 = []
    for res_t1 in res_txt:
        res_tg = re.search('((\|.+\|)+)', res_t1)
        if res_tg is not None:
            res_txt2.append(res_tg.group(1)[1:-1])
    if not res_txt2:
        return pd.DataFrame(None)
    need_pop = []
    for i in range(len(res_txt2)):
        if len(re.findall('-\|-', res_txt2[i].replace(' ', ''))) >= 2:
            need_pop.append(i)
    if len(need_pop) > 1:
        need_pop += list(map(lambda x: x - 1, need_pop[1:]))
    need_pop.sort()
    k = 0
    for i in need_pop:
        res_txt2.pop(i - k)
        k += 1
    is_eq = 0
    need_col = ['类别', '价值', '明细']
    for i1 in need_col:
        if i1 in res_txt2[0]:
            is_eq += 1
    if is_eq < 2:
        return pd.DataFrame(None)
    res_df = []
    for i in res_txt2:
        i = i.replace(' ', '')
        i = i.split('|')
        i = [i1.replace('<br>', '; ') for i1 in i]
        if len(i) > 1:
            res_df.append(i)
    res_df2 = pd.DataFrame(res_df)
    # res_df2 = res_df2.drop([1], axis=0)
    # dp_col = res_df2.apply(lambda x: ((x == '') | (x == '-')).sum(), axis=0)
    # dp_col = dp_col[dp_col > len(res_df2) // 2 + 1].index.tolist()
    # res_df2 = res_df2.drop(dp_col, axis=1)
    if res_df2.shape[1] == 2:
        res_df2.loc[:, -1] = ''
    if res_df2.shape[1] > 3:
        res_df2 = res_df2.drop(res_df2.iloc[0][res_df2.iloc[0].str.contains('期初')].index.tolist(), axis=1)
        res_df2 = res_df2.drop(res_df2.iloc[0][res_df2.iloc[0].str.contains('来源')].index.tolist(), axis=1)
    if res_df2.shape[1] > 3:
        res_df2_1 = res_df2.iloc[:, :2]
        res_df2_2 = res_df2.iloc[:, 2:].apply(lambda x: '; '.join(x.tolist()), axis=1)
        res_df2_1.loc[:, '明细'] = res_df2_2
        res_df2 = res_df2_1.copy()
    res_df2.columns = res_df2.iloc[0]
    res_df2 = res_df2.iloc[1:]
    res_df2.columns = ['项目', '金额', '明细']
    res_df2.loc[:, '项目'] = res_df2.loc[:, '项目'].apply(lambda x: np.where(x == '', None, x)).ffill()
    res_df2.loc[:, '金额'] = res_df2.loc[:, '金额'].apply(lambda x: np.where(x == '', None, x)).fillna('0')
    # res_df2.loc[:, '金额'] = res_df2.loc[:, '金额'].map(lambda x: float(x.replace(',', '')))
    res_df2 = res_df2.groupby('项目').apply(
        lambda x: {
            '项目': x.loc[:, '项目'].iloc[0],
            '金额': sum_amt(x.loc[:, '金额']),
            '明细': '; '.join(x.loc[:, '明细'])
        }
    )
    res_df2 = pd.DataFrame(res_df2.tolist())
    res_df2 = res_df2.set_index('项目')
    return res_df2


if __name__ == '__main__':
    mk1 = '\n\n根据平安银行2024年年度报告提供的材料信息，经全面梳理各章节内容，未发现关于境外债券（非发行）及QDII投资的明细披露。现说明如下：\n\n### 未找到相关数据的原因分析\n1. **境外债券投资披露缺失**：\n   - 材料中仅披露了境内金融债券持仓情况（含政策性银行债、商业银行金融债等），前十大持仓均为境内机构发行的债券\n   - 在金融工具公允价值披露章节中，未发现涉及境外债券的层次划分或估值说明\n   - 资产负债表金融投资科目未单列境外债券项目\n\n2. **QDII投资未专项披露**：\n   - 全文中未出现"QDII"相关关键词\n   - 投资类金融资产明细未包含QDII产品类别\n   - 结构化主体披露仅指向财务报表附注，但提供的材料片段未包含相关细节\n\n### 特别说明\n根据银保监会《商业银行信息披露办法》，商业银行对境外投资需作专项披露。若报告中确实未包含该部分内容，可能属于以下情形：\n1. 持有规模未达到披露门槛\n2. 相关投资通过结构化主体持有，未合并报表\n3. 披露内容被归并到"其他金融资产"科目（2024年末余额189.62亿元）\n\n建议通过以下渠道获取补充信息：\n```markdown\n| 查询渠道          | 联系方式                          | 信息范围                  |\n|-------------------|-----------------------------------|--------------------------|\n| 投资者关系部门    | 电话：0755-22197773               | 特定科目明细数据          |\n| 年报完整版附件    | 深交所官网(股票代码:000001)       | 可能包含分项附表          |\n| 外汇管理局公示系统| 国家外汇管理局网站QDII投资额度审批| QDII资格与额度使用情况    |\n'
    par_mk(mk1)
    # res = request_action('ListDoc', {
    #     'BotBizId': useConfig.bot_biz_zid,
    #     'PageNumber': 1,
    #     'PageSize': 10
    # })
    # print(res)